package provider

import (
	"QImages/database"
	"QImages/entity"
	"QImages/global"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"net/http/cookiejar"
	"strings"
	"sync"
	"time"

	"github.com/bitly/go-simplejson"
	"github.com/google/uuid"
	"github.com/imroc/req"
	"golang.org/x/net/publicsuffix"
)

var (
	imagesUrl = "https://image.so.com/z?ch=wallpaper"
	moreUrl   = "https://image.so.com/zjl?ch=wallpaper&sn=%d&pn=30&prevsn=%d"
	client    *http.Client
	wg        sync.WaitGroup
)

func init() {
	options := cookiejar.Options{
		PublicSuffixList: publicsuffix.List,
	}
	jar, _ := cookiejar.New(&options)
	client = &http.Client{
		Jar: jar,
	}
}

// 爬虫爬取的图片信息的封装
type NetImage struct {
	Url   string `json:"imgurl"`
	Desc  string `json:"pic_desc"`
	Title string `json:"title"`
	Label string `json:"label"`
}

// ToEntity 将爬取的信息转换为数据库存储的格式
func (n NetImage) ToEntity() entity.Image {
	return entity.Image{
		Url:   n.Url,
		Desc:  n.Desc,
		Title: n.Title,
		Label: n.Label,
	}
}

// StoreImages 取出数据
func StoreImages() {
	client.Get(imagesUrl)
	for i := 0; i < 4; i++ {
		wg.Add(1)
		go SolveImage(i)
	}
	wg.Wait()
}

// SolveImage 获取并处理图片数据
func SolveImage(i int) {
	n := rand.Intn(5)
	time.Sleep(time.Duration(n) * time.Second)
	images, err := GetImages(i * 30)
	if err != nil {
		log.Println(err.Error())
	} else {
		if len(images) > 0 {
			for _, item := range images {
				res, err := req.Get(item.Url)
				if err != nil {
					log.Println(err.Error())
					continue
				}
				// imageUrl, err := request.PostImage("demo.png", res.Response().Body)
				// if err != nil {
				// 	log.Println(err.Error())
				// 	continue
				// }
				enImage := item.ToEntity()
				// enImage.Url = imageUrl
				path := global.Config.PhotoPath
				name := strings.ReplaceAll(uuid.New().String(), "-", "") + ".png"
				err = res.ToFile(path + name)
				enImage.Url = name
				if err != nil {
					log.Println(err.Error())
				}
				user := entity.User{}
				database.DB.First(&user)
				enImage.UserID = user.ID
				_, err = enImage.Insert()
				if err != nil {
					log.Println(err.Error())
				}
			}
		}
	}
	wg.Done()
}

// GetImages 根据参数获取图片数据
func GetImages(prevsn int) (images []NetImage, e error) {
	url := fmt.Sprintf(moreUrl, prevsn+30, prevsn)
	res, err := client.Get(url)
	if err != nil {
		e = err
		return
	}
	bs, err := ioutil.ReadAll(res.Body)
	if err != nil {
		e = err
		return
	}
	newJson, err := simplejson.NewJson(bs)
	if err != nil {
		e = err
		return
	}
	array, err := newJson.Get("list").Array()
	if err != nil {
		e = err
		return
	}
	for _, v := range array {
		var image NetImage
		bytes, err := json.Marshal(v)
		if err != nil {
			e = err
			return
		}
		err = json.Unmarshal(bytes, &image)
		if err != nil {
			e = err
			return
		}
		images = append(images, image)
	}
	return
}
